////////////////////////////////////////////////////////////////////////////////

#ifndef _CIRCLEPOLYGONINTERSECTOR_H_
#include "circlepolygonintersector.h"
#endif

#ifndef _CIRCLE_H_
#include "circle.h"
#endif

#ifndef _POLYGON_H_
#include "polygon.h"
#endif

#ifndef _MATHFUNCTIONS_H_
#include "mathfunctions.h"
#endif

////////////////////////////////////////////////////////////////////////////////


void CirclePolygonIntersector::Intersect( PhysicalObject& _obj1, PhysicalObject& _obj2 )
{
    const PE::Circle& sh1 = static_cast<const PE::Circle&>(_obj1.GetShape());
    const PE::Polygon& sh2 = static_cast<const PE::Polygon&>(_obj2.GetShape());

    const PE::Point p1 = _obj1.GetPosition();
    const PE::Point p2 = _obj2.GetPosition();

    // Intersect each line with circle
    for( size_t i = 0; i < sh2.m_Points.size(); ++i )
    {
        size_t j = i+1;
        if ( j == sh2.m_Points.size() )
            j = 0;

        // Create line, line coordinates shifted on object position
        PE::Line line = {sh2.m_Points[i] + p2, sh2.m_Points[j] + p2};

        PE::Point tangency;

        if ( IntersectCircleWithLine( p1, sh1, line, tangency ) )
        {
            // Get impulse direction
            PE::Vector normal = {tangency.x - p1.x, tangency.y - p1.y};
            m_Normal = PE::GetDirection(normal);
            m_WasIntersection = true;
            return;
        }
    }

    m_WasIntersection = false;
}


////////////////////////////////////////////////////////////////////////////////
